let fs = require('fs')
let EventEmitter = require('events')
class ReadStream extends EventEmitter{
    constructor(path, options){
        super(path, options)
        this.path = path;
        this.flags = options.flags || 'r';
        this.mode = options.mode || 0o666;
        this.highWatermark = options.highWatermark || 64*1024;
        this.start = options.start || 0;
        this.end = options.end;
        this.pos = this.start;
        this.encoding = options.encoding;
        this.flowing = null;
        this.buffer = Buffer.alloc(this.highWatermark)
        this.open(); //打开文件读取
        // 当添加任意监听函数时，会触发newListener事件
        this.on('newListener', (type, listener)=>{
            // 监听data事件时，会切换flowing模式
            if(type == 'data'){
                this.flowing = true
                this.read()
            }
        })
    }
    open(){
        fs.open(this.path, this.flags, this.mode, (err, fd)=>{
            if(err) {
                if(this.autoClose){
                    this.destory();
                    return this.emit('error', err)
                }
            }
            this.fd = fd;
            this.emit('open')
        })
    }
    read(){
        if(typeof this.fd != 'number'){
            return this.once('open', ()=>this.read())
        }
        let howMuchToRead = this.end ? Math.min(this.end - this.pos + 1,this.highWatermark): this.highWatermark;
        // this.buffer 并不是缓存区
        fs.read(this.fd, this.buffer,0,howMuchToRead, this.pos, (err, bytes)=>{
            // bytes 是实际读到的字节数
            if(err){
                if(this.autoClose){
                    this.destory()
                }
                return this.emit('error', err)
            }
            if(bytes){
                let data = this.buffer.slice(0, bytes);
                this.pos += bytes;
                data = this.encoding ? data.toString(this.encoding) : data;
                this.emit('data', data)
                console.log(this.flowing)
                if(this.end && this.pos > this.end){
                    return this.emit('end')
                } else {
                    
                    if(this.flowing)
                        this.read()
                }
            } else {
                return this.emit('end')
            }
        })
    }
    destory(){
        fs.close(this.fd, ()=>{
            this.emit('close')
        })
    }

    pipe(dest){
        this.on('data', data=>{
            let flag = dest.write(data)
            if(!flag){
                this.pause()
            }
        })
        dest.on("drain", ()=>{
            this.resume();
        })
    }
    // 当监听data 时，可读流进入流动模式
    pause(){
        this.flowing = false
    }
    resume(){
        this.flowing = true
        this.read()
    }

}

module.exports = ReadStream
